/***********************************************************************
 * Module:  RecordFormatter.java
 * Author:  wy
 * Purpose: Defines the Class RecordFormatter
 ***********************************************************************/

package wxdb.record;

import static java.sql.Types.INTEGER;

import java.util.*;
import wxdb.storage.Page;
import wxdb.storage.StorageMgr;
import wxdb.tx.PageFormatter;
import wxdb.tx.Transaction;
import wxdb.ui.Global;


public class RecordFormatter implements PageFormatter{

   private TableInfo ti;
   
   /** @param page 
    * @param pos
    */
   private void makeDefaultRecord(Page page, int pos) {
	   for (String fldName : ti.getSchema().getFields()) {
	         int offset = ti.getOffset(fldName);
	         if (ti.getSchema().getType(fldName) == INTEGER)
	            Transaction.setInt(ti.getDbid(), page.getPageID(), pos+Transaction.getIntSize()+offset, 0);
	         else
	        	 Transaction.setString(ti.getDbid(), page.getPageID(), pos+Transaction.getIntSize()+offset, "", 0);
	   }
   }
   
   /** @param ti
    */
   public RecordFormatter(TableInfo ti) {
      this.ti = ti;
   }
   
   /** @param page
    */
   public void format(Page page) {
	  byte content[] = new byte[Global.STORAGE_PAGE_SIZE];
	  byte iByte[] = Transaction.int2iByte(RecordPage.EMPTY);
	  int iByteLen = iByte.length;
	  int recordLen = ti.getRecordLen();
	  int slotLen = Transaction.getIntSize() + recordLen;
      for(int pos=0; pos+slotLen<Global.STORAGE_PAGE_SIZE; pos+=slotLen){
    	  int apos = pos;
    	  for(int j=0; j<iByteLen; ++j, ++apos)
    		  content[apos] = iByte[j]; 
      }
      StorageMgr sm = new StorageMgr();
      String key = page.getDataBaseID() + ";" + page.getPageID();
      sm.writeBufPage(content, key);
 //     return 0;
   }

}